/**
 * Copyright (c) 2002-2008 jNETx.
 * http://www.jnetx.com
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * jNETx. You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license
 * agreement you entered into with jNETx.
 *
 * $Id: $
 *
 */
package com.pas.book;

import java.io.DataInputStream;
import java.io.IOException;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;

public class RasterFont {

    private final Image[] glyphs = new Image[256];
    private final int height;

    public RasterFont(String name) {
        try {
            Image image = Image.createImage("/" + name + ".png");
            height = image.getHeight();
            DataInputStream is = new DataInputStream(getClass().getResourceAsStream("/" + name + ".fm"));
            int x = 0;
            for (int i = 32; i < 256; i++) {
                int w = is.readUnsignedByte();
                glyphs[i] = Image.createImage(image, x, 0, w, height, Sprite.TRANS_NONE);
                x += w;
            }
            is.close();
        } catch (IOException e) {
            throw new Error(e.getMessage());
        }
    }

    public Image getGlyph(char ch) {
        return glyphs[CharCode.UnicodeToWin1251(ch)];
    }

    public int getWidth(char ch) {
        Image img = glyphs[CharCode.UnicodeToWin1251(ch)];
        return img  == null ? 0 : img.getWidth();
    }
    
    public int getWidth(char[] chars) {
        int width = 0;
        for (int i = 0; i < chars.length; i++) {
            char ch = chars[i];
            width += getWidth(ch);
        }
        return width;
    }

    public int getWidth(String str) {
        int width = 0;
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            width += getWidth(ch);
        }
        return width;
    }

    public int getHeight() {
        return height;
    }
}
